package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.entity.BaseEntity;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private SpecParamService specParamService;

    @Override
    public List<SpecGroupDTO> queryGroupByCategoryId(Long id) {
        List<SpecGroup> specGroups = query().eq("category_id", id).list();
        return SpecGroupDTO.convertEntityList(specGroups);
    }

    @Override
    public void saveGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        save(specGroup);
    }

    @Override
    public void updateGroup(SpecGroupDTO groupDTO) {
        updateById(groupDTO.toEntity(SpecGroup.class));
    }

    @Override
    @Transactional
    public List<SpecGroupDTO> querySpec(Long categoryId) {
        //根据categoryId查询specGroup集合
        List<SpecGroup> specGroups = query().eq("category_id", categoryId).list();

        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(specGroups);

        //根据specGroup集合中的每个specGroup的groupId查询对应的specParam集合
        /*List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(specGroups)
                .stream().map(specGroupDTO -> {
                    List<SpecParam> specParams = specParamService.query()
                        .eq("group_id", specGroupDTO.getId()).list();
                    specGroupDTO.setParams(SpecParamDTO.convertEntityList(specParams));
                    return specGroupDTO;
        }).collect(Collectors.toList());*/

        //根据categoryId查询所有specParam
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(this.specParamService
                .query().eq("category_id", categoryId).list());

        //将查询到的specParam集合按照GroupId分组
        Map<Long, List<SpecParamDTO>> paramMap = specParamDTOS.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //将specParam组赋值给对应的SpecGroupDTO
        specGroupDTOS.forEach(specGroupDTO->specGroupDTO
                .setParams(paramMap.get(specGroupDTO.getId())));
        return specGroupDTOS;
    }
}
